import { useRef, useEffect } from 'react';

import useHttp from "../../hooks/use-http";
import { addComment } from "../../lib/api";
import LoadingSpinner from "../UI/LoadingSpinner";
import classes from './NewCommentForm.module.css'

const NewCommentForm = (props) => {
  const commentTextRef = useRef();

  const { sendRequest, status, error } = useHttp(addComment);

  const { onAddedComment, quoteId } = props;

  useEffect(() => {
      if (status === 'completed' && !error) {
          onAddedComment();
      }
  },[status, error, onAddedComment]);

  const submitFormHandler = (event) => {
    event.preventDefault();

    const enteredText = commentTextRef.current.value;

    sendRequest( {commentData: {text: enteredText}, quoteId: quoteId });
  };

  return (
    <form className={classes.form} onSubmit={submitFormHandler}>
        {status === 'pending'  && <div className="centered">
            <LoadingSpinner />
        </div>}
      <div className={classes.control} onSubmit={submitFormHandler}>
        <label htmlFor='comment'>你的评论</label>
        <textarea id='comment' rows='5' ref={commentTextRef} />
      </div>
      <div className={classes.actions}>
        <button className='btn'>添加新评论</button>
      </div>
    </form>
  );
};

export default NewCommentForm;
